package cn.xinfei.xdecision.common.service.rpc;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@Component
//@ConditionalOnProperty(name = "xdecision.rpc-context.enabled", havingValue = "true")
public class RpcContextFilter extends OncePerRequestFilter {
    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String rpcContextJson = request.getHeader("Rpc-Context");
        if (rpcContextJson != null) {
            RpcContext currentContext = mapper.readValue(rpcContextJson, RpcContext.class);
            currentContext.put("report_id", UUID.randomUUID().toString().replace("-", ""));
            RpcContext.setCurrentContext(currentContext);
        }
        filterChain.doFilter(request, response);
    }
}